// pages/statistics/index/index.js
import Toast from '../../../vant/toast/toast'
import {
  getOrderList,
  orderRefund,
  getOrderListV2
} from '../../../utils/api/index.js'
import moment from '../../../utils/moment.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active:0,
    isLogin: true,
    refundStatusStr: {
      'CANCEL': '确认收货',
      'REFUNDED': '退款成功',
      'REFUSED': '退款失败'
    },
    orderStatusStr: {
      'CANCEL': '已取消',
      'REFUSED': '系统拒绝',
      'INCOMPLETE': '待完善',
      'UNPAY': '未支付',
      'PAID': '待打单',
      'PRINTED': '待揽收',
      'SHIPPED': '待收货',
      'DELIVERING': '待收货',
      'RECEIVED': '已完成'
    },
    minValue: '',
    maxValue: '',
    transValue: 0,
    wrapperStyle: '',
    downFlag: true,
    orderStatus: '',
    pageNo: 1,
    pageSize: 10,
    orderDate: '',
    totalNum: 0,
    dataList: [],
    isAll: false,
    refundPopupShow: false,
    refundOperation: '',
    refundOrderId: '',
    keyword: '',

    loading: false,
    orderType:"REGULAR",//1、REGULAR：常规订单（包含REGULAR以及BATCH）；2、FRUIT：水果订单。默认值为REGULAR


    trackingNoNum:1,//1是一个包裹,2是多个报错
    trackingNoData:[],//处理过的多个数据 是个数组

    orderId:"",
    // orderType:"",
    isShowRefund: false,
    isShowCancel: false,
    refundOperation: '',
    companyArray:['公司1','公司2'],
    selCompany:{
      companyName: '切分公司'
    },
    selete2Arr: ['苹果'],
    selete2Name: '切果品',
    selete3Arr: ['地区1'],
    selete3Name: '切站点',

    array: ['美国', '中国', '巴西', '日本'],
    index: 0,
    refer:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(6666);
    // this.getOrders()
    wx.getSystemInfo({
      success: function (res) {
        const windowHeight = res.windowHeight
        let minValue = windowHeight * 0.25
        let maxValue = windowHeight * 0.75
        this.setData({
          minValue,
          maxValue
        })
      }.bind(this),
    })
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
    const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
    this.setData({
      orderDate: `${year}-${month}-${day}`
    }) 


    this.setData({
      isLogin: true,
      orderStatus: '',
      pageNo: 1,
      totalNum: 0,
      dataList: [],
      isAll: false,
    })   
    const loginInfo = wx.getStorageSync('loginInfo')
    if (loginInfo) {
      this.setData({
        isLogin: true,
        orderStatus: '',
        pageNo: 1,
        totalNum: 0,
        dataList: [],
        isAll: false
      })
      this.getOrders()
      this.datepicker = this.selectComponent('#datepicker');
    } else {
      this.setData({
        isLogin: false
      })
    }
    // this.setData({
    //   dataList:[]
    // })

  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 获取日期选择器
    this.datepicker = this.selectComponent('#datepicker');
    // this.getOrders()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(app.globalData.type){
      this.setData({
        isLogin: true,
        orderStatus: '',
        pageNo: 1,
        totalNum: 0,
        dataList: [],
        isAll: false,
      })   
      const loginInfo = wx.getStorageSync('loginInfo')
      if (loginInfo) {
        this.setData({
          isLogin: true,
          orderStatus: '',
          pageNo: 1,
          totalNum: 0,
          dataList: [],
          isAll: false
        })
        this.getOrders()
        this.datepicker = this.selectComponent('#datepicker');
      } else {
        this.setData({
          isLogin: false
        })
      }

    }
    app.globalData.type = ''
    
   
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  // 切换公司
  changeCompany(e) {
    console.log(e)
    let index = e.detail.value
    this.setData({
      fruitId: undefined,
      selCompany:{
        companyName: this.data.companyArray[index]
      },
    })
    // // 切换公司时清空页面数据
    // this.clearPageData()
    // app.globalData.fruit = null;

    // console.log("清除");
    // // 清空上次默认选择水果
    // wx.removeStorageSync('selectFruit')

    // // 记录选择分公司
    // wx.setStorageSync('selectCompany', {
    //   companyId: this.data.selCompany.companyId,
    // });
    // // 获取水果列表
    // this.getFruitList()
  },
  changeCompany2(e) {
    console.log(e)
    let index = e.detail.value
    this.setData({
      selete2Name: this.data.selete2Arr[index]
    })
  },
  changeCompany3(e) {
    console.log(e)
    let index = e.detail.value
    this.setData({
      selete3Name: this.data.selete3Arr[index]
    })
  },
  toLogin() {
    wx.navigateTo({
      url: '/pages/mine/login/index',
    })
  },

  // touchStart(e) {
  //   this.data.startY = e.changedTouches[0].clientY
  // },
  // touchEnd(e) {
  //   const endY = e.changedTouches[0].clientY
  //   const startY = this.data.startY
  //   const diff = endY - startY
  //   const absDiff = diff > 0 ? diff : -diff
  //   const middleValue = this.data.maxValue - this.data.minValue

  //   if (diff > 0) {
  //     // 向下滑动
  //     this.toMove(this.data.maxValue - this.data.minValue)
  //     this.datepicker.mulLine()
  //   } else if (diff < 0) {
  //     this.toMove(0)
  //     this.datepicker.singleLine()
  //   }
  // },

  // touchMove(e) {
  //   let timer = null
  //   if (!timer) {
  //     timer = setTimeout(() => {
  //       const clientY = e.changedTouches[0].clientY
  //       if (clientY > this.data.minValue && clientY < this.data.maxValue) {

  //       }
  //       clearTimeout(timer)
  //     }, 1000)
  //   }
  // },
  // // 移动
  // toMove(value) {
  //   const transform = `translate3d(0,${value}px, 0)`;
  //   const transition =
  //     'transform .6s cubic-bezier(0.18, 0.89, 0.32, 1)';
  //   this.setData({
  //     wrapperStyle: `
  //       -webkit-transform: ${transform};
  //       -webkit-transition: ${transition};
  //       transform: ${transform};
  //       transition: ${transition};
  //     `
  //   });
  // },

  statusChange(e) {
    const status = e.target.dataset.type
    this.setData({
      orderStatus: status,
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },
  // 下拉刷新
  onPulling(){
    this.setData({
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },
  // 获取订单列表
  getOrders() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    getOrderListV2({
      // orderDate: this.data.orderDate,
      orderStatus: this.data.orderStatus,
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize,
      keyword: this.data.keyword,
      orderType:this.data.orderType
    }).then(res => {
      if (res.resultStatus) {
        if (res.resultData.dataList.length ==0&&this.data.pageNo>1) {
          Toast('没有更多了')
        }
        if (res.resultData.dataList.length) {
          const resultList = res.resultData.dataList
          // resultList.forEach(f => {
          //   f.createTime = moment(f.createTime).format('MM-DD HH:mm')
          // })
          let dataList = []
          if(this.data.pageNo > 1){
            dataList = this.data.dataList.concat(resultList)
          }else{
            dataList = resultList
          }
          // const dataList = this.data.dataList.concat(resultList)


          // this.setData({
          //   totalNum: res.resultData.totalNum,
          //   dataList
          // })


          let arrNew = dataList.map((item)=>{
            return{
              ...item,
              trackingNo:(item.trackingNo!==null)&&(!Array.isArray(item.trackingNo))?item.trackingNo.split(';'):item.trackingNo,
              
              orderNo:(item.orderNo!==null)&&(!Array.isArray(item.orderNo))?item.orderNo.split(';'):item.orderNo,

              trackingNoNum:item.trackingNo!==null&&item.trackingNo.indexOf(";") != -1?2:1,
            }
          })


          this.setData({
            totalNum: res.resultData.totalNum,
            dataList:arrNew
          })
             
          // this.data.dataList.forEach((item,index)=>{
          //   if(item.trackingNo&&item.trackingNo.indexOf(";") != -1){
          //     let arr = item.trackingNo.split(';')
          //     console.log(arr);
          //     this.setData({
          //        trackingNoNum:2,
          //        'item.trackingNo':arr,
          //      })
               
          //    }else{
          //      this.setData({
          //        trackingNoNum:1,
          //        'item.trackingNo':item.trackingNo,
          //      })
          //    }
   
          // })
          

        } else {

          this.setData({
            isAll: true
          })
        }
        this.setData({
          refer:false
        })
      } else {
        Toast(res.errorMessage)
      }
      wx.hideLoading();
    }).catch(err=>{
      wx.hideLoading();
    })
  },
    // 查看详情
    handleInfo(e){
      
      wx.setStorageSync('nowOrderstatus', e.currentTarget.dataset.item.complainExistStatus)
      const orderId = e.currentTarget.dataset.item.orderId
      wx.navigateTo({
        url: '/pages/statistics/order/index?orderId=' + orderId+'&isOrderFruit='+this.data.orderType,
      })
    },
    goPage(e){
      wx.navigateTo({
        url: '/pages/statistics/complaint/index?orderId=' + e.currentTarget.dataset.item.orderId + '&orderNo=' + e.currentTarget.dataset.item.orderNo
      });
    },
  copy(e){
    console.log(e);
    const data = e.currentTarget.dataset.text || ''
    wx.setClipboardData({data: data})
  },
  // 搜索
  toSearch(e) {
    const keyword = e.detail.value.trim();
    this.setData({
      keyword,
      orderStatus: '',
      dataList: [],
      pageNo: 1
    })
    this.getOrders();
  },

  // 查看详情
  toDetail(e) {
    // console.log(132132132)
    // this.data.dataList.forEach(ele => {
    //   if(ele.orderId == e.detail){
    //     wx.setStorageSync('nowOrderstatus', ele.complainExistStatus)
    //   }
    // })
    // const orderId = e.detail
    //  wx.navigateTo({
    //   url: '/pages/statistics/order/index?orderId=' + orderId,

    // })
  },

  // 申请/取消退款
  // toRefund(e) {
  //   const orderId = e.detail.orderid
  //   const refundStatus = e.detail.refundstatus
  //   if (!refundStatus || refundStatus === 'CANCEL') {
  //     // 申请
  //     this.setData({
  //       refundPopupShow: true,
  //       refundOperation: 'REFUND',
  //       refundOrderId: orderId
  //     })

  //   } else {
  //     // 取消
  //     this.setData({
  //       refundPopupShow: true,
  //       refundOperation: 'CANCEL',
  //       refundOrderId: orderId
  //     })
  //   }
  // },

  // toRefund(e){
  //   const orderType = e.currentTarget.dataset.type

  //   if(orderType=="CANCEL"){
  //     this.setData({
  //       isShowCancel:true,
  //       refundOperation: "CANCEL",
  //     })
  //   }else{
  //     this.setData({
  //       isShowRefund:true,
  //       refundOperation: "REFUND",
  //     })

  //   }

   
  // },



  //取消退款
  toRefund(e){
    console.log(e);
    const orderType = e.currentTarget.dataset.type
    const orderId = e.currentTarget.dataset.orderid


    if(orderType=="CANCEL"){
      this.setData({
        refundOrderId:orderId,
        isShowCancel:true,
        refundOperation: "CANCEL",
      })
    }else{
      this.setData({
        refundOrderId:orderId,
        isShowRefund:true,
        refundOperation: "REFUND",
      })

    }

   
  },


 //取消
 onClose() {
  this.setData({
    isShowRefund: false
  });
},

// 确定
onSubmit() {
  orderRefund({
    orderId: this.data.refundOrderId,
    refundOperation: this.data.refundOperation,
  }).then(res => {
    if (res.resultStatus) {
      Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');


      let a=this.data.dataList
      a.map((item,index)=>{
        if(item.orderId==this.data.refundOrderId)
        item.refundStatus='PENDING'
      })
      this.setData({
        isShowRefund: false,
        dataList:a
      });


      // this.getOrders()
    } else {
      Toast(res.errorMessage);
    }
  })
},

//取消
onClose1() {
  this.setData({
    isShowCancel: false
  });
},

// 确定
onSubmit1() {
  orderRefund({
    orderId: this.data.refundOrderId,
    refundOperation: this.data.refundOperation,
  }).then(res => {
    if (res.resultStatus) {
      Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');
      this.setData({
        isShowCancel: false
      });

      let b=this.data.dataList
      b.map((item,index)=>{
        if(item.orderId==this.data.refundOrderId)
        item.refundStatus=null
      })
      this.setData({
        isShowRefund: false,
        dataList:b
      });


      // this.getOrders()

    } else {
      Toast(res.errorMessage);
    }
  })
},

  handleAction(data) {
    if (data.detail === 'ok' && this.data.refundOrderId && this.data.refundOperation) {
      this.setData({
        refundPopupShow: false
      })
      orderRefund({
        orderId: this.data.refundOrderId,
        refundOperation: this.data.refundOperation
      }).then(res => {
        if (res.resultStatus) {
          Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功')
          const dataList = this.data.dataList.map(f => {
            if (f.orderId === this.data.refundOrderId) {
              f.refundStatus = this.data.refundOperation === 'CANCEL' ? 'CANCEL' : 'PENDING'
            }
            return f
          })
          this.setData({
            dataList,
            refundOperation: '',
            refundOrderId: ''
          })
        } else {
          Toast(res.errorMessage)
        }
      })
    } else {
      this.setData({
        refundPopupShow: false,
        refundOperation: '',
        refundOrderId: ''
      })
    }
  },

  bindscrolltolower() {
    console.log("bindscrolltolower");
    if (!this.data.isAll) {
      this.setData({
        pageNo: this.data.pageNo + 1
      })
      this.getOrders()
    }
  },

  // handleChooseDate(e) {
  //   this.setData({
  //     orderDate: e.detail,
  //     isAll: false,
  //     pageNo: 1,
  //     totalNum: 0,
  //     dataList: []
  //   })
  //   this.toMove(0)
  //   this.datepicker.singleLine()
  //   this.getOrders()
  // },



  toLogisticsOrder(){
    this.setData({
      orderType: 'REGULAR',
    })
    this.setData({
      orderType: 'REGULAR',
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },

  toFruitOrder(){
    this.setData({
      orderType: 'FRUIT',
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },
  toSearch(e){
    console.log(11);
    const orderType=this.data.orderType;
    console.log(orderType);
    wx.navigateTo({
      url: `/pages/dispatch/orderSearch/index?orderType=` + orderType,
    });
  },
  






})